import { post, get } from '@/utils/ajax';
import { getCacheDict } from '@base/api/base/dict/type';
import { customApiExecute, modelApiExecute, localApiExecute, getParamsWithMerge } from './common-methods';
import { useAnvilCodeStore } from '../store/modules/code';

export async function getDynamicCompDicts(that, comp) {
  const {
    dicOption,
    // dicContentType,
    formDataUrl,
    method,
    contentType,
    // dicMethod,
    dicRes,
    // dicQuery,
    dictionary,
    remoteType,
    hookBefore,
    hookAfter,
    // chooseApi,
    selectFirst,
    params,
    noLoading
  } = comp;
  if (dicOption == 'static') {
    if (comp.dicData && comp.dicData.length && selectFirst) {
      comp.value = comp.dicData[0][comp.props.value];
    }
  }
  // 动态获取字典项
  else if (dicOption == 'dictionary' && dictionary) {
    return getCacheDict(dictionary).then((res) => {
      comp.dicData = res.data;
      if (comp.dicData && comp.dicData.length && selectFirst) {
        comp.value = comp.dicData[0][comp.props.value];
      }
    });
  } else if (dicOption == 'remote') {
    try {
      const anvilCodeStore = useAnvilCodeStore();
      const { instance } = anvilCodeStore.getPageForm(that.pageId || that.$attrs.pageId);
      const callback = (response) => {
        let res = response;
        if (hookAfter) {
          console.log('调用后置钩子', hookAfter);
          // 获取当前表单实例
          res = instance[hookAfter](response);
        }
        let dicts = [];
        if (dicRes) {
          dicts = eval(dicRes);
        } else {
          dicts = res;
        }

        console.log('dicts', dicts);
        // 设置dicOption这步必不可少
        comp.dicOption = 'static';
        comp.dicData = dicts;
        if (comp.dicData && comp.dicData.length && selectFirst) {
          comp.value = comp.dicData[0][comp.props.value];
        }
      };

      let Params = getParamsWithMerge(that, params);
      if (hookBefore) {
        console.log('调用前置钩子', hookBefore);
        Params = instance[hookBefore](Params);
      }

      const config = {
        url: formDataUrl,
        method,
        contentType,
        params: Params,
        callback
      };

      switch (remoteType) {
        case 'ajax':
          return customApiExecute(config, { noLoading });
        case 'ajaxModel':
          return modelApiExecute(config, { noLoading });
        case 'ajaxLocal':
          return localApiExecute(config, { noLoading });
      }
    } catch (e) {
      console.error('getDynamicCompDicts Error!', e);
    }
  }
}
